﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyHealthByDesignWebsite.Models;
using System.Web.Security;

namespace MyHealthByDesignWebsite.Controllers
{
    public class MyHealthHistoryController : Controller
    {
        //Description:  Use to get and set Health History model data using the related view
        //Created:  Nov 2011
        //Programmer:  Bob Whiteis
        // Modifications: Kinosha Wimalaratne (Nov 2011 /To connect to the PAR-Q and You)


        MyHealthHistoryRepository uhhRepository = new MyHealthHistoryRepository();
        //
        // GET: /MyHealthHistory/
        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /MyHealthHistory/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /MyHealthHistory/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter health history
        public ActionResult Create()
        {

            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);
            //if the user has already completed this page skip it
            if (MyHeathHistoryComplete(userID))
                return RedirectToAction("HealthRisks", "MyHealthHistory", new { HHFD_FieldID = "DC" });

          
            UserHealthHistory uhh = new UserHealthHistory()
            {
                U_UserID = userID
            };

            ViewData["PregOpts"] = new SelectList(new []{"","Yes", "No", "I do not know."} );
            return View(uhh);
        } 

        //
        // POST: /MyHealthHistory/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition: health history information entered by user has been saved to the database
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            UserHealthHistory uhh = new UserHealthHistory();
            try
            {
                UpdateModel(uhh);
                uhhRepository.Add(uhh);
                uhhRepository.Save();

                return RedirectToAction("HealthRisks", "MyHealthHistory", new { HHFD_FieldID = "DC"});
            }
            catch
            {
                foreach (var issue in uhh.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }

                ViewData["PregOpts"] = new SelectList(new[] { "", "Yes", "No", "I do not know." });
                return View(uhh);
            }
        }
        
        //
        // GET: /MyHealthHistory/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /MyHealthHistory/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /MyHealthHistory/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /MyHealthHistory/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /DiagnosedConditions/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Diagnosed Condition
        public ActionResult HealthRisks()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);
            
            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("DiagnosedDisease", "MyHealthHistory", new {  HHFD_FieldID = "DD" });


            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /DiagnosedConditions/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Diagnosed Conditions information has been saved to the database
        [HttpPost]
        public ActionResult HealthRisks(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("DiagnosedDisease", "MyHealthHistory", new {  HHFD_FieldID = "DD" });
         
        }



        //
        // GET: /DiagnosedDisease/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Diagnosed Disease information
        public ActionResult DiagnosedDisease()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("FamilyHistory", "MyHealthHistory", new { HHFD_FieldID = "FH" });


            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }



        //
        // SET: /DiagnosedDisease/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Diagnosed Diseases information has been saved to the database
        [HttpPost]
        public ActionResult DiagnosedDisease(FormCollection result)
        {
            
            addHealthHistorySection(result);


           return RedirectToAction("FamilyHistory", "MyHealthHistory", new { HHFD_FieldID = "FH" });

        }


        //
        // GET: /FamilyHistory/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Family History information
        public ActionResult FamilyHistory()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("Hypertension", "MyHealthHistory", new { HHFD_FieldID = "HY" });


            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /FamilyHistory/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Family History information has been saved to the database
        [HttpPost]
        public ActionResult FamilyHistory(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("Hypertension", "MyHealthHistory", new {  HHFD_FieldID = "HY" });

        }

        //
        // GET: /Hypertension/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Hypertension information
        public ActionResult Hypertension()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("PhysicalActivity", "MyHealthHistory", new { HHFD_FieldID = "PAL" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /Hypertension/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Hypertension information has been saved to the database
        [HttpPost]
        public ActionResult Hypertension(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("PhysicalActivity", "MyHealthHistory", new { HHFD_FieldID = "PAL" });

        }

        //
        // GET: /PhysicalActivity/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Physical Activity information
        public ActionResult PhysicalActivity()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("Obesity", "MyHealthHistory", new { HHFD_FieldID = "OB" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /PhysicalActivity/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  PhysicalActivity information has been saved to the database
        [HttpPost]
        public ActionResult PhysicalActivity(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("Obesity", "MyHealthHistory", new { HHFD_FieldID = "OB" });

        }

        // GET: /Obesity/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Obesity information
        public ActionResult Obesity()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("Cholesterol", "MyHealthHistory", new { HHFD_FieldID = "CL" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /Obesity/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Obesity information has been saved to the database
        [HttpPost]
        public ActionResult Obesity(FormCollection result)
        {
           
            addHealthHistorySection(result);

            return RedirectToAction("Cholesterol", "MyHealthHistory", new { HHFD_FieldID = "CL" });

        }

        // GET: /Cholesterol/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Cholesterol information 
        public ActionResult Cholesterol()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("Prediabetes", "MyHealthHistory", new { HHFD_FieldID = "DD" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /Cholesterol/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition: Cholesterol  information has been saved to the database
        [HttpPost]
        public ActionResult Cholesterol(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("Prediabetes", "MyHealthHistory", new { HHFD_FieldID = "DD" });

        }

        // GET: /Prediabetes/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Prediabetes information
        public ActionResult Prediabetes()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("CigaretteSmoking", "MyHealthHistory", new { HHFD_FieldID = "CS" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /Prediabetes/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Prediabetes information has been saved to the database
        [HttpPost]
        public ActionResult Prediabetes(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("CigaretteSmoking", "MyHealthHistory", new { HHFD_FieldID = "CS" });

        }

        // GET: /CigaretteSmoking/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Cigarette Smoking information
        public ActionResult CigaretteSmoking()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
                return RedirectToAction("Symptoms", "MyHealthHistory", new { HHFD_FieldID = "SY" });

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /CigaretteSmoking/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Cigarette Smoking information has been saved to the database
        [HttpPost]
        public ActionResult CigaretteSmoking(FormCollection result)
        {
            
            addHealthHistorySection(result);

            return RedirectToAction("Symptoms", "MyHealthHistory", new { HHFD_FieldID = "SY" });

        }

        // GET: /Symptoms/Details
        //pre-condition: UserID has been saved in cookie
        //post-condition:  View has been displayed to allow used to enter Symptoms information
        public ActionResult Symptoms()
        {
            string hh_fieldID = Request.Params["HHFD_FieldID"];
            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //if the user has completed the section skip to the next
            if (MyUserHeathHistorySectionComplete(userID, hh_fieldID))
            {
                //assign the user role HealthCheckComplete
                if (!Roles.IsUserInRole("HealthCheckComplete"))
                    Roles.AddUserToRole(User.Identity.Name, "HealthCheckComplete");
                //Checking age to redirect to Par-Q or questioner 
                if (getAge(userID) > 40)
                    return RedirectToAction("HealthCheckThankYouQuestionnaire", "MyHealthHistory");
                else
                    return RedirectToAction("HealthCheckThankYouPARQ", "MyHealthHistory");
            }

            var healthHistoryFieldsDescs = uhhRepository.GetHealthHistoryDescByType(hh_fieldID).ToList();

            return View(healthHistoryFieldsDescs);
        }

        //
        // SET: /Symptoms/Create
        //pre-condition: UserID has been saved in cookie
        //post-condition:  Symptoms information has been saved to the database
        [HttpPost]
        public ActionResult Symptoms(FormCollection result)
        {
      
            addHealthHistorySection(result);

            //assign the user role HealthCheckComplete
            if (!Roles.IsUserInRole("HealthCheckComplete"))
                Roles.AddUserToRole(User.Identity.Name, "HealthCheckComplete");


            int userID = Convert.ToInt32(Request.Cookies["UserID"].Value);

            //Checking age to redirect to Par-Q or questioner 
            if( getAge(userID) > 40)
                return RedirectToAction("HealthCheckThankYouQuestionnaire", "MyHealthHistory");
            else
                return RedirectToAction("HealthCheckThankYouPARQ", "MyHealthHistory");
        }

        //
        //calculate user's age
        //precondition:  User is logged in and user id is save as a cookie
        //post-condtion:  User's age is return after calculate it using user's date of birth          
        public int getAge(int userID)
        {
            FullDataSetDataContext db = new FullDataSetDataContext();
            

            User user = db.Users.Single(u => u.U_userID == userID);

            int age = DateTime.Now.Year - user.U_DOB.GetValueOrDefault().Year;            

            return age;
        }



        //adds health history 
        //precondition:  User is logged in and user id is save as a cookie
        //post-condtion:  True is return if user has completed the health history
        private bool addHealthHistorySection(FormCollection result)
        {
            try
            {
                int UserID = Convert.ToInt32(Request.Cookies["UserID"].Value);

                var healthHistoryItems = from item in result.AllKeys
                                         where result[item] != "false"
                                         select item;

                string otherDescID = "";
                // add each health history item that was marked true
                foreach (var fieldDescID in healthHistoryItems)
                {
                    UserHealthHistoryFieldsDesc uhhfd = new UserHealthHistoryFieldsDesc();
                    uhhfd.U_userID = UserID;

                    HealthHistoryFieldsDesc hhfd = new HealthHistoryFieldsDesc();
                    string hhfd_desc;
                    if (fieldDescID != "otherText")
                    {
                        hhfd = uhhRepository.GetHealthHistoryFieldDesc(fieldDescID);
                        hhfd_desc = hhfd.HHFD_desc;
                    }
                    else
                        hhfd_desc = "";

                    if (hhfd_desc == "Other")
                    {
                        otherDescID = fieldDescID;
                        continue;
                    }
                    else
                        uhhfd.HHFD_fieldDescID = fieldDescID;

                    if (fieldDescID == "otherText")
                    {
                        uhhfd.HHFD_fieldDescID = otherDescID;
                        uhhfd.UHHFD_OtherSpecify = fieldDescID;
                    }

                    uhhRepository.AddUserHealthHistoryFields(uhhfd);
                    uhhRepository.Save();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }


        //returns true if the user has completed the initial my health history page
        //precondition:  User is logged in and user id is save as a cookie
        //post-condtion:  True is return if user has completed the intial health history
        public bool MyHeathHistoryComplete(int userID)
        {
            FullDataSetDataContext db = new FullDataSetDataContext();
            if (db.UserHealthHistories.Any(n => n.U_UserID == userID))
                return true;
            else
                return false;
        }


        //returns true if the user has completed the section of user health history
        //precondition:  User is logged in and user id is save as a cookie
        //post-condtion:  True is return if user has completed the related section of the health history
        public bool MyUserHeathHistorySectionComplete(int userID, string healthHistorySection)
        {
            FullDataSetDataContext db = new FullDataSetDataContext();
           if (db.UserHealthHistoryFieldsDescs.Any(u => u.U_userID == userID && u.HHFD_fieldDescID.Contains(healthHistorySection) ))
                return true;
            else
                return false;
        }


        //
        // GET: /HealthCheckThankYouPARQ/
        //pre-condition: UserID has been saved in cookie and user's age should be <= 40
        //post-condition:  Displaying thank you page for PAR-Q and YOU        
        public ActionResult HealthCheckThankYouPARQ()
        {
            return View();
        }


        //
        // SET: /HealthCheckThankYouPARQ/
        //pre-condition: UserID has been saved in cookie and user's age should be <= 40
        //post-condition: Rederecting to PARQNYOU page
        [HttpPost]
        public ActionResult HealthCheckThankYouPARQ(FormCollection collection)
        {

            return RedirectToAction("PARQNYOU", "PARQ");
        }


        //
        // GET: /HealthCheckThankYouQuestionnaire/
        //pre-condition: UserID has been saved in cookie and user's age should be >40
        //post-condition:  Displaying thank you page for Questionnaire/   
        public ActionResult HealthCheckThankYouQuestionnaire()
        {
            return View();
        }

        //
        // SET: /HealthCheckThankYouQuestionnaire/
        //pre-condition: UserID has been saved in cookie and user's age should be >40
        //post-condition: Rederecting to Questionnaire page
        [HttpPost]
        public ActionResult HealthCheckThankYouQuestionnaire(FormCollection collection)
        {

            return RedirectToAction("Questionnaire", "PARQ");
        }

        
    }
}
